package com.hhhn.wk.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * * * * * * * * * * * *
 * @author：WenKe ｡◕‿◕｡ *
 * Data：2017     ｡◕‿◕｡ *
 * QQ：370820580  ｡◕‿◕｡ *
 * Function：     ｡◕‿◕｡ *
 * 存取User表数据
 * * * * * * * * * * * */

public class SharePreferencesUser {
	private static final String NAME = "userShare";

	public static SharedPreferences getSharedPreferences(Context context) {
		return context.getSharedPreferences(NAME, Context.MODE_APPEND);
	}
/**
     * 存放实体类以及任意类型
     * @param context 上下文对象
     * @param key 
     * @param obj
     */
	public static void putBean(Context context, String key, Object obj) {
		if (obj instanceof Serializable) {// obj必须实现Serializable接口，否则会出问题
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(baos);
				oos.writeObject(obj);
				String string64 = new String(Base64.encode(baos.toByteArray(),
						0));
				Editor editor = getSharedPreferences(context).edit();
				editor.putString(key, string64);
				editor.commit();
			} catch (IOException e) {
				e.printStackTrace();
			}

		} else {
			throw new IllegalArgumentException(
					"the obj must implement Serializble");
		}

	}
	//读取
	public static Object getBean(Context context, String key) {
		Object obj = null;
		try {
			String base64 = getSharedPreferences(context).getString(key, "");
			if (base64.equals("")) {
				return null;
			}
			byte[] base64Bytes = Base64.decode(base64.getBytes(), 1);
			ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			obj = ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	//清空
	public static void getclear(Context context, String key) {
		try {
			SharedPreferences sp = getSharedPreferences(context);
			if (sp==null) {
				return ;
			}
			Editor editor = sp.edit();
			editor.clear();
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//读取打印
	public static Object getBeanDY(Context context, String key) {
		Object obj = null;
		try {

			String base64 = getSharedPreferences(context).getString(key, "");
			Log.d("读取打印", "getBeanDY: "+base64);
//			if (base64.equals("")) {
//				return null;
//			}
//			byte[] base64Bytes = Base64.decode(base64.getBytes(), 1);
//			ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
//			ObjectInputStream ois = new ObjectInputStream(bais);
//			obj = ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}
